package MyGui;

import java.awt.*;
import java.awt.event.*;
import java.io.*;
import javax.swing.*;
import java.text.NumberFormat;

import DistSys.*;
import Element.AbsElem;
import Element.Geom.AbsElemGeom;

public class ExportDataDlg extends MyDlgFrame implements ActionListener{
    private JComboBox     comboType;
    private ZoneComboBox  comboZone;
    private JList         lstData,
                          lstResult;
    private JButton       btnExport;
    private double        dZone;
    private int           iSelectedType;

    public ExportDataDlg(MainFrame parent, String title) {
        super(parent, title);
        Container pane = this.getContentPane();
        pane.setLayout(gridBagLayout);

        comboZone = new ZoneComboBox();
        JLabel lblZone = new JLabel("Area:");
        lblZone.setDisplayedMnemonic('A');
        lblZone.setLabelFor(comboZone);

        comboType = new JComboBox(SysConst.ssType);
        JLabel lblType = new JLabel("Component Type:");
        lblType.setDisplayedMnemonic('T');
        lblType.setLabelFor(comboType);

        lstData = new JList(SysConst.ssDataField);
        lstData.setSelectionMode(
            DefaultListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
        JScrollPane scrollData = new JScrollPane(lstData);
        scrollData.setPreferredSize(new Dimension(150, 150));

        lstResult = new JList(SysConst.ssResultField);
        lstResult.setSelectionMode(
            DefaultListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
        JScrollPane scrollResult = new JScrollPane(lstResult);
        scrollResult.setPreferredSize(new Dimension(150, 150));

        JPanel panelData = new JPanel(MyDlgFrame.gridBagLayout);
        JPanel panelResult = new JPanel(MyDlgFrame.gridBagLayout);

        btnExport = new JButton("Output to Excel");
        btnExport.setMnemonic('O');
        btnExport.addActionListener( this);

        GridBagConstraints c = new GridBagConstraints();
        c.insets = new Insets(GAP, GAP, 0, 0);
        c.anchor = GridBagConstraints.WEST;
        c.fill = GridBagConstraints.HORIZONTAL;
        c.gridy = 0;
        c.gridx = 0; c.gridwidth = 1; c.weightx = 0; c.insets.right = 0;
        pane.add(lblZone, c);
        c.gridx = 1; c.gridwidth = 2; c.weightx = 1; c.insets.right = GAP;
        pane.add(comboZone, c);
        c.gridy = 1;
        c.gridx = 0; c.gridwidth = 1; c.weightx = 0; c.insets.right = 0;
        pane.add(lblType, c);
        c.gridx = 1; c.gridwidth = 2; c.weightx = 1; c.insets.right = GAP;
        pane.add(comboType, c);

        c.fill = GridBagConstraints.BOTH;
        c.gridy = 2; c.weighty = 1; c.insets.left = c.insets.right = 0;
        c.gridx = 0; c.gridwidth = 2; pane.add(panelData, c);
        c.insets.left = GAP;
        c.gridx = 2; c.gridwidth = 1; pane.add(panelResult, c);

        c.anchor = GridBagConstraints.CENTER; c.fill = GridBagConstraints.NONE;
        c.gridy = 3; c.weighty = 0; c.insets.right = c.insets.bottom = GAP;
        c.gridx = 0; c.gridwidth = 3; pane.add(btnExport, c);

        panelData.setBorder(BorderFactory.createTitledBorder(
            BorderFactory.createEtchedBorder(), " Data Fields to Export "));
        panelResult.setBorder(BorderFactory.createTitledBorder(
            BorderFactory.createEtchedBorder(), " Result Fields to Export "));
        c.fill = GridBagConstraints.BOTH;
        c.gridy = 0; c.weighty = 1;
        c.insets.top = 0; c.insets.left = c.insets.right = c.insets.bottom = 5;
        panelData.add(scrollData, c);
        panelResult.add(scrollResult, c);

        this.setDefaultCloseOperation(JDialog.HIDE_ON_CLOSE);
        this.setSize(500,340);
        this.setLocation(200,200);
        // this.setResizable(false);
    }

    public void actionPerformed(ActionEvent evt){
        Object o = evt.getSource();
        if( o == btnExport ){
            try{
                dZone = comboZone.getSelectedZone();
            }catch (ZoneComboBox.ZoneException e){
                JOptionPane.showMessageDialog(mainFrame,
                    "'" + e.getMessage() + "' is not a valid zone.");
                return;
            }

            iSelectedType = SysConst.mapIndexToType(
                comboType.getSelectedIndex());
            if( iSelectedType == SysConst.TYPE_NONE) {
                JOptionPane.showMessageDialog(mainFrame,
                    "Please choose a type.");
                return;
            }

            int[] aiData = lstData.getSelectedIndices();
            int[] aiResult=lstResult.getSelectedIndices();

            try{
                File f = Sys.personalInfo.createTempExportFile();
                BufferedWriter bw = new BufferedWriter(new FileWriter(f));

                writeExportHeader( bw, aiData, aiResult);
                int cntr = writeExportRows( bw, aiData, aiResult);
                bw.close();
                if( cntr == 0){
                    JOptionPane.showMessageDialog(this,
                      "No matching components founded.\n");
                } else {
                    Sys.personalInfo.execExcel(f.getPath());
                }
            }catch (IOException e){
                JOptionPane.showMessageDialog(this, "Error occured when " +
                    "writing to the temporary export file.\n" + e);
                return;
            }catch(Exception e){
                JOptionPane.showMessageDialog(this,e);
                return;
            }
        }//end of btnExport
    }
/* Original
    private void writeExportHeader( BufferedWriter bw, int[] aiData,
                                    int[] aiResult) throws IOException{

        bw.write("\"Performance Advantange Reliability Analysis\"\n");
        bw.write("\"\"\n");
        bw.write("\"\"\n");

        bw.write("\"ID\",\"Name\",\"Type\",\"Default Template\",");
        if( aiData.length>=1 && aiData[0]!=0 ){
            for(int k=0; k<aiData.length; k++){
                bw.write("\""+ SysConst.ssDataField[ aiData[k] ] +"\",");
            }
        }
        if( aiResult.length>=1 && aiResult[0]!=0 ){
            for(int k=0; k<aiResult.length; k++){
                bw.write("\""+ SysConst.ssResultField[aiResult[k]]+"\",");
            }
        }
        bw.write("\n");
    }*/
    
    private void writeExportHeader( BufferedWriter bw, int[] aiData,
            						int[] aiResult) throws IOException{

    	bw.write("\"Performance Advantange Reliability Analysis\"\n");
    	bw.write("\"\"\n");
    	bw.write("\"\"\n");

    	bw.write("\"ID\",\"Name\",\"Type\",\"Default Template\",");
    	if( aiData.length>=1 && aiData[0]!=0 ){
    			for(int k=0; k<aiData.length; k++){
    				bw.write("\""+ SysConst.ssDataField[ aiData[k] ] +"\",");
    			}
    	}
    	if( aiResult.length>=1 && aiResult[0]!=0 ){
    			for(int k=0; k<aiResult.length; k++){
    				bw.write("\""+ SysConst.ssResultField[aiResult[k]]+"\",");
    			}
    	}
    	bw.write("\n");
    }
    
    private int writeExportRows( BufferedWriter bw, int[] aiData,
                                  int[] aiResult)throws IOException{
        int cntr=0;
        AbsElem elem;
        AbsElemGeom geom;
        double val=0.0;
        String str;

        NumberFormat nf = NumberFormat.getNumberInstance();
        nf.setMaximumFractionDigits(4);
        nf.setGroupingUsed(false);

        int sz = Sys.elemList.size();
        for(int i=0;i<sz;i++){
            elem = (AbsElem) Sys.elemList.elementAt(i);
            geom = elem.getElemGeomObj();

            //skip these elements
            if (!Zone.getZoneFits(dZone, elem) ||
                (iSelectedType != SysConst.TYPE_ALL &&
                 iSelectedType != elem.getType()))
                continue;

            //ExternalId = InternalId + 1
            str = "" + (i+1) + ",\"" + geom.getName() + "\",\"" +
                  elem.getStringForType() + "\",\"" +
                  elem.getDftTempName() + "\",";

            if( aiData.length>=1 && aiData[0]!=0 ){
                for(int k=0; k<aiData.length; k++){
                    val = elem.getData(
                        SysConst.mapDataIndexFromDisplayToValue( aiData[k] ));
                    str += nf.format( val )+",";
                }
            }
            if( aiResult.length>=1 && aiResult[0]!=0 ){
                for(int k=0; k<aiResult.length; k++){
                    val = elem.getResult(
                        SysConst.mapResultIndexFromDisplayToValue( aiResult[k]));
                    str += nf.format( val )+",";
                }
            }
            str +="\n";
            bw.write(str);
            cntr++;
        }//end of for loop
        return cntr;
    }

}